﻿using System;
using System.Drawing;
using System.Windows.Forms;
using S7PlcDataCollector.Client.Tools;

namespace S7PlcDataCollector.Client.Controls
{
    public partial class MenuControl : UserControl
    {
        public event Action<int> MenuItemClick = (menuTag) => { };

        private MenuItemAlignment _alignment = MenuItemAlignment.Horizontal;
        private MenuItemControl _currentMenuItem;

        public MenuControl()
        {
            InitializeComponent();

            menuItemPlcList.Tag = Constants.MenuTag.PlcList;
            menuItemRealtimeData.Tag = Constants.MenuTag.RealtimeData;

            Paint += MenuControl_Paint;
        }

        private void MenuControl_Load(object sender, EventArgs e)
        {
            ResizeControls();
            OnMenuItemClick(menuItemPlcList);
            menuItemPlcList.Selected = true;

            menuItemPlcList.MenuItemClicked += OnMenuItemClick;
            menuItemRealtimeData.MenuItemClicked += OnMenuItemClick;
        }

        private void MenuControl_Resize(object sender, EventArgs e)
        {
            ResizeControls();
        }

        private void MenuControl_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            var p = new Pen(Color.Gray, 1);
            g.DrawRectangle(p, Width - 1, 0, Width, Height);
        }

        private void ResizeControls()
        {
            if (_alignment == MenuItemAlignment.Horizontal)
            {
                menuItemPlcList.Left = 20;
                menuItemPlcList.Top = (ClientSize.Height - menuItemPlcList.Height) / 2;
                menuItemRealtimeData.Left = menuItemPlcList.Right + 20;
                menuItemRealtimeData.Top = menuItemPlcList.Top;
            }
            else
            {
                menuItemPlcList.Left = (ClientSize.Width - menuItemPlcList.Width) / 2;
                menuItemPlcList.Top = 20;
                menuItemRealtimeData.Left = menuItemPlcList.Left;
                menuItemRealtimeData.Top = menuItemPlcList.Bottom + 20;
            }
        }

        public void SetAlignment(MenuItemAlignment alignment)
        {
            _alignment = alignment;
        }

        private void OnMenuItemClick(MenuItemControl menuItem)
        {
            if (_currentMenuItem != null)
            {
                _currentMenuItem.Selected = false;
            }

            if (menuItem != null)
            {
                menuItem.Selected = true;
            }

            _currentMenuItem = menuItem;
            var menuTag = (int?) menuItem?.Tag ?? 0;
            MenuItemClick?.Invoke(menuTag);
        }

        public enum MenuItemAlignment
        {
            /// <summary>
            /// 水平排列
            /// </summary>
            Horizontal,

            /// <summary>
            /// 垂直排列
            /// </summary>
            Vertical
        }
    }
}
